package edu.cmu.vlis.wassup.publisher;

import javax.jms.JMSException;
import javax.jms.ObjectMessage;

import org.mybeans.factory.RollbackException;

import com.sun.messaging.Topic;

import edu.cmu.vlis.wassup.databean.Event;
import edu.cmu.vlis.wassup.databean.UnprocessedEvent;
import edu.cmu.vlis.wassup.db.UnprocessedEventDAO;
import edu.cmu.vlis.wassup.db.UnprocessedEventTagDAO;

public class UserEventPoller extends AbstractPoller{

    UnprocessedEventDAO upd = null;
    UnprocessedEventTagDAO upt = null;
    private int id;

    public UserEventPoller(Integer port){
        super(20000);
        id = port;
        
    }

    public void initialize() throws Exception{
        this.upd = new UnprocessedEventDAO();
        this.upt = new UnprocessedEventTagDAO(); 

    }
    public  int getMessagesNputInPublisherQ() {
        UnprocessedEvent events[] = null;
        if(this.upd == null || this.upt == null){
            try {
                initialize();
            } catch (Exception e) {
                e.printStackTrace();
                return -1;
            }
        }

        try {
            events =  this.upd.getAll();
            for(UnprocessedEvent event : events) {
            	
            	System.out.println("got event " + event);
                ObjectMessage objMesg = this.topicSession.createObjectMessage(event);

                //find all the topic in it
                String[] topicList =this.upt.getTagForEvent(event);
                //Place in Event Bean according to topic.
                for(String topic : topicList) {
                	System.out.println("Got topic " + topic);
                    this.topicPublisher.publish(new Topic(topic), objMesg);
                }
                //this.upd.delete(event.getHashId());
//                (event.getHashId());
            }
        } 
//        catch (DAOException e) {
//            e.printStackTrace();
//            return -1;
//        }
        catch (JMSException e) {
            e.printStackTrace();
            return -1;
        } 
        return events.length;
    }

    public String getPollerName() {
        return "UserEventPoller";
    }

    @Override
    public int getID() {
        // TODO Auto-generated method stub
        return this.id;
    }

}
